﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ErpCoreModel;
using ErpCoreModel.Base;
using ErpCoreModel.Framework;
using ErpCoreModel.Report;
using ErpCoreModel.UI;
using MongoDB.Bson;
using MongoDB.Driver;

public partial class Security_User_UserPanel : System.Web.UI.Page
{
    public CUser m_User = null;
    public CTable m_Table = null;
    public CCompany m_Company = null;
    public CView m_View = null;
    public Guid m_guidParentId = Guid.Empty;
    AccessType m_ViewAccessType = AccessType.forbide;
    AccessType m_TableAccessType = AccessType.forbide;
    //受限的字段：禁止或者只读权限
    SortedList<Guid, AccessType> m_sortRestrictColumnAccessType = new SortedList<Guid, AccessType>();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["User"] == null)
        {
            Response.Redirect("../../Login.aspx");
            Response.End();
        }
        m_User = (CUser)Session["User"];
        if (!m_User.IsRole("管理员"))
        {
            Response.Write("没有管理员权限！");
            Response.End();
        }

        string B_Company_id = Request["B_Company_id"];
        if (string.IsNullOrEmpty(B_Company_id))
            m_Company = Global.GetCtx(Session["TopCompany"].ToString()).CompanyMgr.FindTopCompany();
        else
            m_Company = (CCompany)Global.GetCtx(Session["TopCompany"].ToString()).CompanyMgr.Find(new Guid(B_Company_id));

        m_Table = (CTable)Global.GetCtx(Session["TopCompany"].ToString()).UserMgr.Table;

        m_View = (CView)Global.GetCtx(Session["TopCompany"].ToString()).ViewMgr.FindFirstByTable(m_Table.Id);
        if (m_View == null)
        {
            Response.Write("视图不存在！");
            Response.End();
        }

        //检查权限
        if (!CheckAccess())
        {
            Response.End();
        }

        if (Request.Params["Action"] == "GetData")
        {
            GetData();
            Response.End();
        }
        else if (Request.Params["Action"] == "Delete")
        {
            Delete();
            Response.End();
        }
    }
    //检查权限
    bool CheckAccess()
    {
        //判断视图权限
        m_ViewAccessType = m_User.GetViewAccess(m_View.Id);
        if (m_ViewAccessType == AccessType.forbide)
        {
            Response.Write("没有视图权限！");
            return false;
        }

        //判断表权限
        m_TableAccessType = m_User.GetTableAccess(m_Table.Id);
        if (m_TableAccessType == AccessType.forbide)
        {
            Response.Write("没有表权限！");
            return false;
        }
        else if (m_TableAccessType == AccessType.read)
        {
        }
        else
        {
        }
        m_sortRestrictColumnAccessType = m_User.GetRestrictColumnAccessTypeList(m_Table);

        return true;
    }

    void GetData()
    {
        int page = Convert.ToInt32(Request.Params["page"]);
        int pageSize = Convert.ToInt32(Request.Params["pagesize"]);
        long totalCount = 0;

        string sData = "";
        List<CBaseObject> lstObj = new List<CBaseObject>();
        if (!m_Table.IsLowChange)
        {
            totalCount = Global.GetCtx(Session["TopCompany"].ToString()).UserMgr.GetCount();
            //当数据量大时，skip会影响翻页性能，我们使用最后的Created时间排序来查询条件提高性能
            //string sCookieKey = "Security_User_UserPanel_LastCreated";
            //if (Session[sCookieKey] == null)
            //{
                int nSkip = (page - 1) * pageSize; // 开始记录数  
                lstObj = Global.GetCtx(Session["TopCompany"].ToString()).UserMgr.GetList(null, null, nSkip, pageSize);
            //}
            //else
            //{
            //    string sCreated = Session[sCookieKey].ToString();
            //    DateTime Created = DateTime.FromOADate(Convert.ToDouble(sCreated));
            //    var filter = Builders<BsonDocument>.Filter.Gt("created", Created);
            //    var sort = Builders<BsonDocument>.Sort.Ascending("created");
            //    lstObj = Global.GetCtx(Session["TopCompany"].ToString()).UserMgr.GetList(filter, sort, 0, pageSize);
            //}
            ////使用cookie保存最新created
            //if (lstObj.Count > 0)
            //{
            //    string val = lstObj[lstObj.Count-1].Created.ToOADate().ToString();
            //    Session[sCookieKey] = val;
            //}
        }
        else
        {
            lstObj = Global.GetCtx(Session["TopCompany"].ToString()).UserMgr.GetList();
            totalCount = lstObj.Count;
        }

        long totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1; // 计算总页数
        
        int index = (page - 1) * pageSize; // 开始记录数  
        if (!m_Table.IsLowChange)
            index = 0;
        for (int i = index; i < pageSize + index ; i++)
        {
            if (i >= lstObj.Count)
                break;
            CBaseObject obj = (CBaseObject)lstObj[i];

            string sRow="";
            foreach (CBaseObject objC in m_Table.ColumnMgr.GetList())
            {
                CColumn col = (CColumn)objC;
                if (col.ColType == ColumnType.object_type)
                {
                    string sVal = "";
                    if (obj.GetColValue(col) != null)
                        sVal = "long byte";
                    sRow += string.Format("\"{0}\":\"{1}\",", col.Code, sVal);
                }
                //else if (col.ColType == ColumnType.ref_type)
                //{
                //    CTable RefTable = (CTable)Global.GetCtx(Session["TopCompany"].ToString()).TableMgr.Find(col.RefTable);
                //    if (RefTable == null) continue;
                //    CBaseObjectMgr objRefMgr = new CBaseObjectMgr();
                //    objRefMgr.TbCode = RefTable.Code;
                //    objRefMgr.Ctx = Global.GetCtx(Session["TopCompany"].ToString());

                //    CColumn RefCol = (CColumn)RefTable.ColumnMgr.Find(col.RefCol);
                //    CColumn RefShowCol = (CColumn)RefTable.ColumnMgr.Find(col.RefShowCol);
                //    string sWhere = string.Format(" {0}=?", RefCol.Code);
                //    List<DbParameter> cmdParas = new List<DbParameter>();
                //    cmdParas.Add(new DbParameter(RefCol.Code, obj.GetColValue(col)));
                //    List<CBaseObject> lstObj2 = objRefMgr.GetList(sWhere, cmdParas);
                //    string sVal = "";
                //    if (lstObj2.Count > 0)
                //    {
                //        CBaseObject obj2 = lstObj2[0];
                //        object objVal = obj2.GetColValue(RefShowCol);
                //        if (objVal != null)
                //            sVal = objVal.ToString();
                //    }
                //    sRow += string.Format("\"{0}\":\"{1}\",", col.Code, sVal);
                //}
                else
                {
                    string sVal = "";
                    object objVal = obj.GetColValue(col);
                    if (objVal != null)
                        sVal = objVal.ToString();
                    Util.ConvertJsonSymbol(ref sVal);
                    sRow += string.Format("\"{0}\":\"{1}\",", col.Code, sVal);
                }

            }
            sRow = sRow.TrimEnd(",".ToCharArray());
            sRow = "{" + sRow + "},";
            sData += sRow;
        }
        sData = sData.TrimEnd(",".ToCharArray());
        sData = "[" + sData + "]";
        string sJson = string.Format("{{\"Rows\":{0},\"Total\":\"{1}\"}}"
            , sData, totalCount);

        Response.Write(sJson);
    }
    void Delete()
    {
        string delid = Request["delid"];
        if (string.IsNullOrEmpty(delid))
        {
            Response.Write("请选择记录！");
            return;
        }
        Global.GetCtx(Session["TopCompany"].ToString()).UserMgr.Delete(new Guid(delid));
        if (!Global.GetCtx(Session["TopCompany"].ToString()).UserMgr.Save(true))
        {
            Response.Write("删除失败！");
            return;
        }
    }
    public List<CColumn> GetColList()
    {
        List<CColumn> lstRet = new List<CColumn>();
        List<CBaseObject> lstObjCIV = m_View.ColumnInViewMgr.GetList();
        for (int i = 0; i < lstObjCIV.Count; i++)
        {
            CColumnInView civ = (CColumnInView)lstObjCIV[i];
            CColumn col = (CColumn)m_Table.ColumnMgr.Find(civ.FW_Column_id);
            if (col == null)
                continue;
            lstRet.Add(col);
        }
        return lstRet;
    }
}
